package com.chiancloud.shield.server.services.utility;

import com.chiancloud.shield.core.main.LauncherExitCodes;
import com.chiancloud.shield.core.main.RunService;
import com.chiancloud.shield.server.services.workflow.WorkflowCompositeService;
import com.google.common.base.Preconditions;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.service.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by wanghui on 14-8-20.
 */
public class LaunchedWorkflowCompositeService extends WorkflowCompositeService implements RunService {
    private static final Logger log = LoggerFactory.getLogger(
            LaunchedWorkflowCompositeService.class);
    private String[] argv;

    public LaunchedWorkflowCompositeService(String name) {
        super(name);
    }

    public LaunchedWorkflowCompositeService(String name, Service... children) {
        super(name, children);
    }

    protected static boolean isUnset(String s) {
        return StringUtils.isEmpty(s);
    }

    protected static boolean isSet(String s) {
        return StringUtils.isNotEmpty(s);
    }

    protected String[] getArgv() {
        return argv;
    }
    @Override
    public Configuration bindArgs(Configuration config, String... args) throws
            Exception {
        this.argv = args;
        if (log.isDebugEnabled()) {
            log.debug("Binding {} Arguments:", args.length);

            StringBuilder builder = new StringBuilder();
            for (String arg : args) {
                builder.append('"').append(arg).append("\" ");
            }
            log.debug(builder.toString());
        }
        return config;
    }

    @Override
    public int runService() throws Throwable {
        return LauncherExitCodes.EXIT_SUCCESS;
    }

    @Override
    public synchronized void addService(Service service) {
        Preconditions.checkArgument(service != null, "null service argument");
        super.addService(service);
    }
    protected boolean deployChildService(Service service) {
        service.init(getConfig());
        addService(service);
        if (isInState(STATE.STARTED)) {
            service.start();
            return true;
        }
        return false;
    }
}
